package cn.virens.common.spring.filter;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.virens.common.exception.APIException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.cors.CorsUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public abstract class AbstractPathMatcherFilter extends OncePerRequestFilter {
    protected final Logger logger = LoggerFactory.getLogger(getClass());

    protected final List<String> blacklist = new ArrayList<>();
    protected final List<String> whitelist = new ArrayList<>();

    private final PathMatcher m = new AntPathMatcher();

    private String mWebApplicationContextName;

    /**
     * 添加需要放行的路径(如果为空全拦截)
     */
    public void addWhitePatterns(String pattern) {
        this.whitelist.add(pattern);
    }

    /**
     * 添加需要拦截的路径(如果为空全拦截)
     */
    public void addBlackPatterns(String pattern) {
        this.blacklist.add(pattern);
    }

    public String getWebApplicationContextName() {
        return mWebApplicationContextName;
    }

    public void setWebApplicationContextName(String mWebApplicationContextAttributeName) {
        this.mWebApplicationContextName = mWebApplicationContextAttributeName;
    }

    protected WebApplicationContext findWebApplicationContext() throws APIException {
        if (mWebApplicationContextName == null || mWebApplicationContextName.isEmpty()) {
            return WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        } else {
            return WebApplicationContextUtils.getWebApplicationContext(getServletContext(), mWebApplicationContextName);
        }
    }

    protected <T> T getBean(String name, Class<T> requiredType) throws APIException {
        return findWebApplicationContext().getBean(name, requiredType);
    }

    protected <T> T getBean(Class<T> requiredType) throws APIException {
        return findWebApplicationContext().getBean(requiredType);
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        if (CollUtil.isNotEmpty(blacklist) && !match(blacklist, request)) return true;
        if (CollUtil.isNotEmpty(whitelist) && match(whitelist, request)) return true;

        return false;
    }

    private boolean match(List<String> patterns, HttpServletRequest request) {
        return match(patterns, request.getRequestURI());
    }

    protected boolean match(List<String> patterns, String path) {
        Iterator<String> iterator = patterns.iterator();

        while (path != null && iterator.hasNext()) {
            if (m.match(iterator.next(), path)) {
                return true;//
            }
        }

        return false;
    }

    protected static boolean isJsonRequest(HttpServletRequest request) throws APIException {
        if (!StrUtil.containsAnyIgnoreCase(request.getContentType(), "application/json")) {
            if (!StrUtil.endWithIgnoreCase(request.getRequestURI(), ".json")) {
                return CorsUtils.isCorsRequest(request);
            } else {
                return true;
            }
        } else {
            return true;
        }
    }
}
